#include <stdio.h>
#include "gd32f30x.h"
#include "i2c.h"
#include "systick.h"
#include "message.h"
#include "update.h"
#include <string.h>

#if I2C1_MODE == I2C1_MODE_POLL
/**
 * PB10 PB11 config I2C1
*/
void i2c1_config(void)
{
    /* enable GPIOB clock */
    rcu_periph_clock_enable(RCU_GPIOB);
    /* enable I2C1 clock */
    rcu_periph_clock_enable(RCU_I2C1);
    /* connect PB10 to I2C1_SCL */
    /* connect PB11 to I2C2_SDA */
    gpio_init(GPIOB, GPIO_MODE_AF_OD, GPIO_OSPEED_50MHZ, GPIO_PIN_10 | GPIO_PIN_11);//配置PB10,PB11为复用功能

    /* configure I2C clock */
    i2c_clock_config(I2C1, I2C1_SPEED, I2C_DTCY_2);
    /* configure I2C address */
    i2c_mode_addr_config(I2C1, I2C_I2CMODE_ENABLE, I2C_ADDFORMAT_7BITS, I2C1_SLAVE_ADDR);
    /* enable I2C1 */
    i2c_enable(I2C1);
    /* enable acknowledge */
    i2c_ack_config(I2C1, I2C_ACK_ENABLE);
}

void i2c1_write_data_by_reg(uint8_t slave_addr,uint8_t* p_buffer, uint8_t write_address, uint8_t number_of_byte)
{
    /* wait until I2C bus is idle */
    while(i2c_flag_get(I2C1, I2C_FLAG_I2CBSY));
    
    /* send a start condition to I2C bus */
    i2c_start_on_bus(I2C1);
    
    /* wait until SBSEND bit is set */
    while(!i2c_flag_get(I2C1, I2C_FLAG_SBSEND));
    
    /* send slave address to I2C bus */
    i2c_master_addressing(I2C1, slave_addr, I2C_TRANSMITTER);
    
    /* wait until ADDSEND bit is set */
    while(!i2c_flag_get(I2C1, I2C_FLAG_ADDSEND));
    
    /* clear the ADDSEND bit */
    i2c_flag_clear(I2C1,I2C_FLAG_ADDSEND);
    
    /* wait until the transmit data buffer is empty */
    while( SET != i2c_flag_get(I2C1, I2C_FLAG_TBE));
    
    /* send the EEPROM's internal address to write to : only one byte address */
    i2c_data_transmit(I2C1, write_address);
    
    /* wait until BTC bit is set */
    while(!i2c_flag_get(I2C1, I2C_FLAG_BTC));
    
    /* while there is data to be written */
    while(number_of_byte--){  
        i2c_data_transmit(I2C1, *p_buffer);
        
        /* point to the next byte to be written */
        p_buffer++; 
        
        /* wait until BTC bit is set */
        while(!i2c_flag_get(I2C1, I2C_FLAG_BTC));
    }
    /* send a stop condition to I2C bus */
    i2c_stop_on_bus(I2C1);
    
    /* wait until the stop condition is finished */
    while(I2C_CTL0(I2C1)&0x0200);
}

void i2c1_read_data_by_reg(uint8_t slave_addr,uint8_t* p_buffer, uint8_t read_address, uint16_t number_of_byte)
{  
    /* wait until I2C bus is idle */
    while(i2c_flag_get(I2C1, I2C_FLAG_I2CBSY));

    if(2 == number_of_byte){
        i2c_ackpos_config(I2C1,I2C_ACKPOS_NEXT);
    }
    
    /* send a start condition to I2C bus */
    i2c_start_on_bus(I2C1);
    
    /* wait until SBSEND bit is set */
    while(!i2c_flag_get(I2C1, I2C_FLAG_SBSEND));
    
    /* send slave address to I2C bus */
    i2c_master_addressing(I2C1, slave_addr, I2C_TRANSMITTER);
    
    /* wait until ADDSEND bit is set */
    while(!i2c_flag_get(I2C1, I2C_FLAG_ADDSEND));
    
    /* clear the ADDSEND bit */
    i2c_flag_clear(I2C1,I2C_FLAG_ADDSEND);
    
    /* wait until the transmit data buffer is empty */
    while(SET != i2c_flag_get( I2C1 , I2C_FLAG_TBE));

    /* enable I2C1*/
    i2c_enable(I2C1);
    
    /* send the EEPROM's internal address to write to */
    i2c_data_transmit(I2C1, read_address);  
    
    /* wait until BTC bit is set */
    while(!i2c_flag_get(I2C1, I2C_FLAG_BTC));
    
    /* send a start condition to I2C bus */
    i2c_start_on_bus(I2C1);
    
    /* wait until SBSEND bit is set */
    while(!i2c_flag_get(I2C1, I2C_FLAG_SBSEND));
    
    /* send slave address to I2C bus */
    i2c_master_addressing(I2C1, slave_addr, I2C_RECEIVER);

    if(number_of_byte < 3){
        /* disable acknowledge */
        i2c_ack_config(I2C1,I2C_ACK_DISABLE);
    }
    
    /* wait until ADDSEND bit is set */
    while(!i2c_flag_get(I2C1, I2C_FLAG_ADDSEND));
    
    /* clear the ADDSEND bit */
    i2c_flag_clear(I2C1,I2C_FLAG_ADDSEND);
    
    if(1 == number_of_byte){
        /* send a stop condition to I2C bus */
        i2c_stop_on_bus(I2C1);
    }
    
    /* while there is data to be read */
    while(number_of_byte){
        if(3 == number_of_byte){
            /* wait until BTC bit is set */
            while(!i2c_flag_get(I2C1, I2C_FLAG_BTC));

            /* disable acknowledge */
            i2c_ack_config(I2C1,I2C_ACK_DISABLE);
        }
        if(2 == number_of_byte){
            /* wait until BTC bit is set */
            while(!i2c_flag_get(I2C1, I2C_FLAG_BTC));
            
            /* send a stop condition to I2C bus */
            i2c_stop_on_bus(I2C1);
        }
        
        /* wait until the RBNE bit is set and clear it */
        if(i2c_flag_get(I2C1, I2C_FLAG_RBNE)){
            /* read a byte from the EEPROM */
            *p_buffer = i2c_data_receive(I2C1);
            
            /* point to the next location where the byte read will be saved */
            p_buffer++; 
            
            /* decrement the read bytes counter */
            number_of_byte--;
        } 
    }
    
    /* wait until the stop condition is finished */
    while(I2C_CTL0(I2C1)&0x0200);
    
    /* enable acknowledge */
    i2c_ack_config(I2C1,I2C_ACK_ENABLE);

    i2c_ackpos_config(I2C1,I2C_ACKPOS_CURRENT);
}

#elif I2C1_MODE == I2C1_MODE_DMA
uint8_t i2c1_buff_rx[128];

static void i2c1_dma_rx_config(uint8_t *p_data,uint8_t len)
{
    dma_parameter_struct dma_init_struct;
    /* initialize DMA channel4 */
    dma_deinit(DMA0, DMA_CH4);
    dma_init_struct.direction = DMA_PERIPHERAL_TO_MEMORY;
    dma_init_struct.memory_addr = (uint32_t)p_data;
    dma_init_struct.memory_inc = DMA_MEMORY_INCREASE_ENABLE;
    dma_init_struct.memory_width = DMA_MEMORY_WIDTH_8BIT;
    dma_init_struct.number = len;
    dma_init_struct.periph_addr = (uint32_t)&I2C_DATA(I2C1);
    dma_init_struct.periph_inc = DMA_PERIPH_INCREASE_DISABLE;
    dma_init_struct.periph_width = DMA_PERIPHERAL_WIDTH_8BIT;
    dma_init_struct.priority = DMA_PRIORITY_ULTRA_HIGH;
    dma_init(DMA0, DMA_CH4, &dma_init_struct);
}

static void i2c1_dma_tx_config(uint8_t *p_data,uint8_t len)
{
    dma_parameter_struct dma_init_struct;
    /* initialize DMA channel3 */
    dma_deinit(DMA0, DMA_CH3);
    dma_init_struct.direction = DMA_MEMORY_TO_PERIPHERAL;
    dma_init_struct.memory_addr = (uint32_t)p_data;
    dma_init_struct.memory_inc = DMA_MEMORY_INCREASE_ENABLE;
    dma_init_struct.memory_width = DMA_MEMORY_WIDTH_8BIT;
    dma_init_struct.number = len;
    dma_init_struct.periph_addr = (uint32_t)&I2C_DATA(I2C1);
    dma_init_struct.periph_inc = DMA_PERIPH_INCREASE_DISABLE;
    dma_init_struct.periph_width = DMA_PERIPHERAL_WIDTH_8BIT;
    dma_init_struct.priority = DMA_PRIORITY_ULTRA_HIGH;
    dma_init(DMA0, DMA_CH3, &dma_init_struct);
}

void i2c1_dma_init(void)
{
    /* enable GPIOB clock */
    rcu_periph_clock_enable(RCU_GPIOB);
    rcu_periph_clock_enable(RCU_DMA0);

    /* enable I2C1 clock */
    rcu_periph_clock_enable(RCU_I2C1);
    /* connect PB10 to I2C1_SCL */
    /* connect PB11 to I2C2_SDA */
    gpio_init(GPIOB, GPIO_MODE_AF_OD, GPIO_OSPEED_50MHZ, GPIO_PIN_10 | GPIO_PIN_11);//配置PB10,PB11为复用功能

    /* configure I2C clock */
    i2c_clock_config(I2C1, I2C1_SPEED, I2C_DTCY_2);
    /* configure I2C address */
    i2c_mode_addr_config(I2C1, I2C_I2CMODE_ENABLE, I2C_ADDFORMAT_7BITS, 0xff);
    /* enable I2C1 */
    i2c_enable(I2C1);
    /* enable acknowledge */
    i2c_ack_config(I2C1, I2C_ACK_ENABLE);
}


static void i2c1_dma_tx_data(uint8_t slave_addr,uint8_t *p_data,uint8_t len)
{
    /* wait until I2C bus is idle */
    while(i2c_flag_get(I2C1, I2C_FLAG_I2CBSY));
    
    /* send a start condition to I2C bus */
    i2c_start_on_bus(I2C1);
    
    /* wait until SBSEND bit is set */
    while(!i2c_flag_get(I2C1, I2C_FLAG_SBSEND));
    
    /* send slave address to I2C bus */
    i2c_master_addressing(I2C1, slave_addr, I2C_TRANSMITTER);
    
    /* wait until ADDSEND bit is set */
    while(!i2c_flag_get(I2C1, I2C_FLAG_ADDSEND));
    
    /* clear the ADDSEND bit */
    i2c_flag_clear(I2C1,I2C_FLAG_ADDSEND);
    
    /* wait until the transmit data buffer is empty */
    while( SET != i2c_flag_get(I2C1, I2C_FLAG_TBE));

    i2c1_dma_tx_config(p_data,len);
    
      /* enable I2C1 DMA */
    i2c_dma_config(I2C1, I2C_DMA_ON);

    /* enable DMA0 channel3 */
    dma_channel_enable(DMA0, DMA_CH3);

    /* DMA0 channel3 full transfer finish flag */
    while(!dma_flag_get(DMA0, DMA_CH3, DMA_FLAG_FTF));
    /* send a stop condition to I2C bus */
    i2c_stop_on_bus(I2C1);
    
    /* wait until the stop condition is finished */
    while(I2C_CTL0(I2C1)&0x0200);  
}
/**
 * 封装一个函数按寄存器写的函数，寄存器地址可以有多位。
 * 数据可以有多个
 * dma方式
*/
void i2c1_dma_send_data(uint8_t slave_addr,uint8_t *reg_addr,
                        uint16_t addr_len,uint8_t *p_data,uint8_t data_len)
{
    uint8_t data[I2C_TX_RX_DATA_LEN_MAX] = {0};
    uint8_t *p;
    if ((addr_len + data_len) > I2C_TX_RX_DATA_LEN_MAX)
    {
        perror("data to long and return\r\n");
        return ;
    }
    p = data;
    memcpy(p,reg_addr,addr_len);
    p += addr_len;
    memcpy(p,p_data,data_len);

    i2c1_dma_tx_data(slave_addr,data,(addr_len+data_len));

}

void i2c1_dma_receive_data(uint8_t slave_addr, uint8_t *reg_addr,uint16_t addr_len,  
            uint8_t* p_buffer, uint16_t number_of_byte)
{  
    /* wait until I2C bus is idle */
    while(i2c_flag_get(I2C1, I2C_FLAG_I2CBSY));

    /* send a start condition to I2C bus */
    i2c_start_on_bus(I2C1);
    
    /* wait until SBSEND bit is set */
    while(!i2c_flag_get(I2C1, I2C_FLAG_SBSEND));
    
    /* send slave address to I2C bus */
    i2c_master_addressing(I2C1, slave_addr, I2C_TRANSMITTER);
    
    /* wait until ADDSEND bit is set */
    while(!i2c_flag_get(I2C1, I2C_FLAG_ADDSEND));
    
    /* clear the ADDSEND bit */
    i2c_flag_clear(I2C1,I2C_FLAG_ADDSEND);
    
    /* wait until the transmit data buffer is empty */
    while(SET != i2c_flag_get( I2C1 , I2C_FLAG_TBE));

    /* enable I2C1*/
    i2c_enable(I2C1);
    
    /* send the EEPROM's internal address to write to */
    while (addr_len)
    {
        i2c_data_transmit(I2C1, *reg_addr++); 
        addr_len--; 
        /* wait until BTC bit is set */
        while(!i2c_flag_get(I2C1, I2C_FLAG_BTC));
    }
    
    /* send a start condition to I2C bus */
    i2c_start_on_bus(I2C1);
    
    /* wait until SBSEND bit is set */
    while(!i2c_flag_get(I2C1, I2C_FLAG_SBSEND));
    
    /* send slave address to I2C bus */
    i2c_master_addressing(I2C1, slave_addr, I2C_RECEIVER);

    /* wait until ADDSEND bit is set */
    while(!i2c_flag_get(I2C1, I2C_FLAG_ADDSEND));
    
    /* clear the ADDSEND bit */
    i2c_flag_clear(I2C1,I2C_FLAG_ADDSEND);

    if(number_of_byte < 2) 
    {
        /* disable acknowledge */
        i2c_ack_config(I2C1, I2C_ACK_DISABLE);
        /* clear ADDSEND register by reading I2C_STAT0 then I2C_STAT1 register (I2C_STAT0 has already been read) */
        i2c_flag_get(I2C1, I2C_FLAG_ADDSEND);
        /* send a stop condition to I2C bus*/
        i2c_stop_on_bus(I2C1);
        /* wait for the byte to be received */
        while(!i2c_flag_get(I2C1, I2C_FLAG_RBNE));
        /* read the byte received from the EEPROM */
        *p_buffer = i2c_data_receive(I2C1);
        /* decrement the read bytes counter */
        number_of_byte--;     
    } 
    else
    {
        i2c1_dma_rx_config(p_buffer,number_of_byte);
        i2c_dma_last_transfer_config(I2C1, I2C_DMALST_ON);
        /* enable I2C1 DMA */
        i2c_dma_config(I2C1, I2C_DMA_ON);
        /* enable DMA0 channel5 */
        dma_channel_enable(DMA0, DMA_CH4);
        /* wait until BTC bit is set */
        while(!dma_flag_get(DMA0, DMA_CH4, DMA_FLAG_FTF));
    }
    /* wait until the stop condition is finished */
    while(I2C_CTL0(I2C1)&0x0200);
    i2c_stop_on_bus(I2C1);

    /* enable acknowledge */
    i2c_ack_config(I2C1,I2C_ACK_ENABLE);
    i2c_ackpos_config(I2C1,I2C_ACKPOS_CURRENT);

}
#elif I2C1_MODE == I2C1_MODE_SLAVE

volatile uint8_t        i2c_txbuffer[128] = {0};
volatile uint8_t        i2c_rxbuffer[128];
volatile uint16_t       i2c_rx_num;
volatile uint16_t       i2c_tx_num;
static   uint8_t        isfirst = 0;

void i2c1_slave_config(void)
{
    /* enable GPIOB clock */
    rcu_periph_clock_enable(RCU_GPIOB);
    /* enable I2C1 clock */
    rcu_periph_clock_enable(RCU_I2C1);
    /* connect PB10 to I2C1_SCL */
    /* connect PB11 to I2C2_SDA */
    gpio_init(GPIOB, GPIO_MODE_AF_OD, GPIO_OSPEED_50MHZ, GPIO_PIN_10 | GPIO_PIN_11);//配置PB10,PB11为复用功能

    /* configure I2C clock */
    i2c_clock_config(I2C1, I2C1_SPEED, I2C_DTCY_2);
    /* configure I2C address */
    i2c_mode_addr_config(I2C1, I2C_I2CMODE_ENABLE, I2C_ADDFORMAT_7BITS, I2C1_OWN_ADDRESS7);
    /* enable I2C1 */
    i2c_enable(I2C1);
    /* enable acknowledge */
    i2c_ack_config(I2C1, I2C_ACK_ENABLE);

    nvic_irq_enable(I2C1_EV_IRQn, 0, 2);
    nvic_irq_enable(I2C1_ER_IRQn, 0, 1);
    /* enable the I2C1 interrupt */
    i2c_interrupt_enable(I2C1, I2C_INT_ERR);
    i2c_interrupt_enable(I2C1, I2C_INT_BUF);
    i2c_interrupt_enable(I2C1, I2C_INT_EV);

}

/*!
    \brief      handle I2C1 event interrupt request
    \param[in]  none
    \param[out] none
    \retval     none
*/
void I2C1_EventIRQ_Handler(void)
{
    if(i2c_interrupt_flag_get(I2C1, I2C_INT_FLAG_ADDSEND)) {
        /* clear the ADDSEND bit */
        if (isfirst == 0)
        {
            isfirst = 1;
            i2c_rx_num = 0; 
        }
        else
        {
            isfirst = 0;
            i2c_tx_num = 0;
            send_i2c_message(i2c_rxbuffer,i2c_rx_num);
        }
        i2c_interrupt_flag_clear(I2C1, I2C_INT_FLAG_ADDSEND);
    } else if((i2c_interrupt_flag_get(I2C1, I2C_INT_FLAG_TBE)) && (!i2c_interrupt_flag_get(I2C1, I2C_INT_FLAG_AERR))) {
        
        /* send a data byte */ 
        //printf("now send data  %d: \r\n",i2c_tx_num);
        i2c_data_transmit(I2C1, i2c_txbuffer[i2c_tx_num++]);
    } else if(i2c_interrupt_flag_get(I2C1, I2C_INT_FLAG_RBNE)) {
        /* if reception data register is not empty ,I2C1 will read a data from I2C_DATA */
        i2c_rxbuffer[i2c_rx_num] = i2c_data_receive(I2C1);
        i2c_rx_num++;

    } else if(i2c_interrupt_flag_get(I2C1, I2C_INT_FLAG_STPDET)) {

        //printf("get num == %d\r\n",i2c_rx_num);
        handle_i2c_message(i2c_rxbuffer,i2c_rx_num);
        /* clear the STPDET bit */
        i2c_enable(I2C1);
        i2c_rx_num = 0;
        i2c_tx_num = 0;
        isfirst = 0;
    }
}


/*!
    \brief      handle I2C1 error interrupt request
    \param[in]  none
    \param[out] none
    \retval     none
*/
void I2C1_ErrorIRQ_Handler(void)
{
    /* no acknowledge received */
    if(i2c_interrupt_flag_get(I2C1, I2C_INT_FLAG_AERR)) {
        i2c_interrupt_flag_clear(I2C1, I2C_INT_FLAG_AERR);
    }

    /* SMBus alert */
    if(i2c_interrupt_flag_get(I2C1, I2C_INT_FLAG_SMBALT)) {
        i2c_interrupt_flag_clear(I2C1, I2C_INT_FLAG_SMBALT);
    }

    /* bus timeout in SMBus mode */
    if(i2c_interrupt_flag_get(I2C1, I2C_INT_FLAG_SMBTO)) {
        i2c_interrupt_flag_clear(I2C1, I2C_INT_FLAG_SMBTO);
    }

    /* over-run or under-run when SCL stretch is disabled */
    if(i2c_interrupt_flag_get(I2C1, I2C_INT_FLAG_OUERR)) {
        i2c_interrupt_flag_clear(I2C1, I2C_INT_FLAG_OUERR);
    }

    /* arbitration lost */
    if(i2c_interrupt_flag_get(I2C1, I2C_INT_FLAG_LOSTARB)) {
        i2c_interrupt_flag_clear(I2C1, I2C_INT_FLAG_LOSTARB);
    }

    /* bus error */
    if(i2c_interrupt_flag_get(I2C1, I2C_INT_FLAG_BERR)) {
        i2c_interrupt_flag_clear(I2C1, I2C_INT_FLAG_BERR);
    }

    /* CRC value doesn't match */
    if(i2c_interrupt_flag_get(I2C1, I2C_INT_FLAG_PECERR)) {
        i2c_interrupt_flag_clear(I2C1, I2C_INT_FLAG_PECERR);
    }
    // /* disable the I2C1 interrupt */
    // i2c_interrupt_disable(I2C1, I2C_INT_ERR);
    // i2c_interrupt_disable(I2C1, I2C_INT_BUF);
    // i2c_interrupt_disable(I2C1, I2C_INT_EV);
}
#elif I2C1_MODE == I2C1_MODE_SW
#include "timer.h"

#define swi2c_sda_high gpio_bit_set(GPIOB,GPIO_PIN_11)
#define swi2c_sda_low  gpio_bit_reset(GPIOB,GPIO_PIN_11)
#define swi2c_sda_read gpio_input_bit_get(GPIOB,GPIO_PIN_11)

#define swi2c_scl_high gpio_bit_set(GPIOB,GPIO_PIN_10)
#define swi2c_scl_low  gpio_bit_reset(GPIOB,GPIO_PIN_10)


void swi2c_config(void)
{   /* enable GPIOB clock */
    rcu_periph_clock_enable(RCU_GPIOB);
    /*PB10 PB11配置成输出 */
	gpio_init(GPIOB, GPIO_MODE_OUT_OD, GPIO_OSPEED_50MHZ, GPIO_PIN_10);
	gpio_init(GPIOB, GPIO_MODE_OUT_OD, GPIO_OSPEED_50MHZ, GPIO_PIN_11);

    swi2c_sda_high;
    swi2c_scl_high;  
    timer3_config();  
}

void delay_1us(uint16_t us)
{
    tim3_delay_us(us);
}

/**
 * SDA PB11 input mode
*/
static void swi2c_sda_config_input_mode(void)
{
    gpio_init(GPIOB, GPIO_MODE_IPU, GPIO_OSPEED_50MHZ, GPIO_PIN_11);
}

/**
 * SDA PB11 output mode
*/
static void swi2c_sda_config_output_mode(void)
{
    gpio_init(GPIOB, GPIO_MODE_OUT_PP, GPIO_OSPEED_50MHZ, GPIO_PIN_11);
}

//开始信号
void swi2c_start(void)
{
	swi2c_sda_config_output_mode(); //SDA定义为输出
	swi2c_sda_high; 
	swi2c_scl_high;
	delay_1us(4);
	swi2c_sda_low;  
	delay_1us(4);
	swi2c_scl_low; 
} 


void swi2c_stop(void)//停止信号
{
	swi2c_sda_config_output_mode(); //SDA定义为输出
	swi2c_scl_low;
	swi2c_sda_low; 
	delay_1us(4);
	swi2c_scl_high; 
	delay_1us(4);
	swi2c_sda_high; //发送 I2C 总线结束信号
	delay_1us(4); 
}

uint8_t swi2c_wait_ack(void)//等待应答信号：0-应答；1-非应答
{
    uint8_t uc_time = 0;
	swi2c_sda_high;
	swi2c_sda_config_input_mode(); //SDA定义为输入 
	delay_1us(4); 
	swi2c_scl_high;
	delay_1us(1);

    while (swi2c_sda_read)
    {
        uc_time++;
        if (uc_time > 250)
        {
            swi2c_stop();
            return 1;
        }
    }
	delay_1us(4);
	swi2c_scl_low;
	return 0; 
} 

void swi2c_ack(void)//产生 ACK 应答
{ 
	swi2c_scl_low;
	swi2c_sda_config_output_mode();
	swi2c_sda_low;
	delay_1us(2);
	swi2c_scl_high;
	delay_1us(2);
	swi2c_scl_low;
}

void swi2c_no_ack(void)//产生 NACK 非应答
{ 
	swi2c_scl_low;
	swi2c_sda_config_output_mode();
	swi2c_sda_high;
	delay_1us(2);
	swi2c_scl_high;
	delay_1us(2);
	swi2c_scl_low;
} 

//IIC 发送一个字节
void swi2c_write_byte(uint8_t txd)
{ 
	uint8_t t; 
	swi2c_sda_config_output_mode(); 
	swi2c_scl_low;            //拉低时钟开始数据传输
	for(t = 0;t < 8;t++)
	{ 
        if((txd<<t) & 0x80)//表示数据是1
			swi2c_sda_high;
		else
			swi2c_sda_low;
		delay_1us(4); 
		swi2c_scl_high;
		delay_1us(4); 
		swi2c_scl_low;
		//delay_us(2);
	}
} 

//读一个字节
uint8_t swi2c_read_byte(void)
{ 
	uint8_t i,receive = 0;
	
	swi2c_sda_config_input_mode();
	for(i = 0;i < 8;i++ )
	{  
		delay_1us(4);
		swi2c_scl_high;
		receive <<= 1;
		if(swi2c_sda_read == 1)
		{
			receive ++;
		}
		delay_1us(4); 
		swi2c_scl_low;
	}
	return receive;
} 

//只写地址
uint8_t write_device_addr(uint8_t addr)
{
	uint8_t read_ack = 0;
	swi2c_start();
	swi2c_write_byte(addr);
	read_ack = swi2c_wait_ack();
	swi2c_stop();
	
	return(read_ack);
}

//在总线上搜寻挂载的器件地址
void swi2c_search_device_addr(void)
{
	uint8_t result = 0;
	uint8_t j = 0;
	for(j = 0;j < 128; j++)
	{
		if((j % 16) == 0)
		{
			printf("\r\n");
		}
		result = write_device_addr(j << 1);
		if(result == 0)
		{
			printf(" %X ",j << 1);//%X 十六进制输出，大写；%x 小写
		}
		else
		{
			printf(" -- ");
		}
	}
    printf("\r\n");
}

//读指定器件的指定位置中的一个字节
uint8_t swi2c_device_read_one_byte(uint8_t device_addr,uint8_t reg_addr)
{
	uint8_t dat;

	swi2c_start();
	swi2c_write_byte(device_addr);//写地址,7位地址左移，低位补0
	swi2c_wait_ack();//等待应答

	swi2c_write_byte(reg_addr);//写位置
	swi2c_wait_ack();

	swi2c_start();
	swi2c_write_byte((device_addr) | 0x01);//读写位改为读
	swi2c_wait_ack();

	dat = swi2c_read_byte();
	swi2c_no_ack();//读一个字节结束
	swi2c_stop();
	
	return dat;
}

void swi2c_device_write_one_byte(uint8_t device_addr,uint8_t reg_addr,uint8_t data)//写指定器件的指定位置中的一个字节
{
	swi2c_start();
	swi2c_write_byte(device_addr);//写地址,7位地址左移，低位补0
	swi2c_wait_ack();//等待应答

	swi2c_write_byte(reg_addr);//写位置
	swi2c_wait_ack();

	swi2c_write_byte(data);//写数据
	swi2c_wait_ack();

	swi2c_stop();
}

//连续读指定器件的指定位置中的多个字节
void swi2c_device_read_bytes(uint8_t device_addr,uint8_t reg_addr,uint8_t *buf,uint8_t len)
{
	swi2c_start();
	swi2c_write_byte(device_addr);//写地址,7位地址左移，低位补0
	swi2c_wait_ack();//等待应答

	swi2c_write_byte(reg_addr);//写位置
	swi2c_wait_ack();

	swi2c_start();
	swi2c_write_byte((device_addr) | 0x01);//读写位改为读
	swi2c_wait_ack();

	while(len > 1)
	{
		*buf++ = swi2c_read_byte();
		swi2c_ack();
		len--;
	}
	*buf = swi2c_read_byte();//循环体结束指针已经指向最后一个字节存放位置
	swi2c_no_ack();//读一个字节结束
	swi2c_stop();	
}

//连续写指定器件的指定位置中的多个字节
void swi2c_device_write_bytes(uint8_t device_addr,uint8_t reg_addr,uint8_t *buf,uint8_t len)
{
	while(len > 0)
	{
		swi2c_start();
		swi2c_write_byte(device_addr);//写地址,7位地址左移，低位补0
		swi2c_wait_ack();//等待应答

		swi2c_write_byte(reg_addr++);//写位置
		swi2c_wait_ack();

		swi2c_write_byte(*buf++);//写数据
		swi2c_wait_ack();

		swi2c_stop();//发送完结束信号后，器件才会把数据进行擦写操作，搬运到非易失区，这段时间器件不再响应主机操作
		delay_1ms(10);//eeprom连续写时必须加，否则下个字节写入失败
		len--;
	}
}

void swi2c_device_write_data(uint8_t device_addr,uint8_t *reg_addr,
                                    uint16_t reg_len,uint8_t *buf,uint8_t len)
{
    swi2c_start();
	swi2c_write_byte(device_addr);//写地址,7位地址左移，低位补0
	swi2c_wait_ack();//等待应答

	while(reg_len)
    {
	    swi2c_write_byte(*reg_addr++);//写位置
	    swi2c_wait_ack();
        reg_len--;
    }

    while(len)
    {
	    swi2c_write_byte(*buf++);//写位置
	    swi2c_wait_ack();
        len--;
    }
    swi2c_stop();
}

void swi2c_write_data(uint8_t device_addr,uint8_t *buf,uint8_t len)
{
    swi2c_start();
	swi2c_write_byte(device_addr);//写地址,7位地址左移，低位补0
	swi2c_wait_ack();//等待应答

    while(len)
    {
	    swi2c_write_byte(*buf++);//写位置
	    swi2c_wait_ack();
        len--;
    }
    swi2c_stop();
}

void swi2c_device_read_data(uint8_t device_addr,uint8_t *reg_addr,
                                    uint16_t reg_len,uint8_t *buf,uint8_t len)
{
	swi2c_start();
	swi2c_write_byte(device_addr);//写地址,7位地址左移，低位补0
	swi2c_wait_ack();//等待应答

    while (reg_len/* condition */)
    {
        /* code */
        swi2c_write_byte(*reg_addr++);//写位置
        swi2c_wait_ack();
        reg_len--;
    }
    
	swi2c_start();
	swi2c_write_byte((device_addr) | 0x01);//读写位改为读
	swi2c_wait_ack();

	while(len > 1)
	{
		*buf++ = swi2c_read_byte();
		swi2c_ack();
		len--;
	}
	*buf = swi2c_read_byte();//循环体结束指针已经指向最后一个字节存放位置
	swi2c_no_ack();//读一个字节结束
	swi2c_stop();	
}

void swi2c_read_data(uint8_t device_addr,uint8_t *buf,uint8_t len)
{
	swi2c_start();
	swi2c_write_byte((device_addr) | 0x01);//读写位改为读
	swi2c_wait_ack();

	while(len > 1)
	{
		*buf++ = swi2c_read_byte();
		swi2c_ack();
		len--;
	}
	*buf = swi2c_read_byte();//循环体结束指针已经指向最后一个字节存放位置
	swi2c_no_ack();//读一个字节结束
	swi2c_stop();	
}

#endif
